package com.yangit.temp.util.barcode;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
 
public class QRCodeGenerator {
	
	private static final String QR_CODE_IMAGE_PATH = "E:/MyQRCode.png";
	
	/**
	 *- 生成二维码图片
	 * @param text 二维码内容
	 * @param width 二维码宽度（像素）
	 * @param height 二维码高宽度（像素）
	 * @param filePath 二维码生成存储路径
	 * @throws WriterException
	 * @throws IOException
	 */
	public static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		
		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
		
		Path path = FileSystems.getDefault().getPath(filePath);
		
		MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
		
	}
	
	/**
	 *- 生成二维码流
	 * @param text 二维码内容
	 * @param width 二维码宽度（像素）
	 * @param height 二维码高宽度（像素）
	 * @param filePath 二维码生成存储路径
	 * @throws WriterException
	 * @throws IOException
	 */
	public static void generateQRCodeStream(String text, int width, int height, OutputStream ops) throws WriterException, IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		
		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
		
		MatrixToImageWriter.writeToStream(bitMatrix, "PNG", ops);
		
	}
	
	/**
	 *- 生成二维码字节流
	 * @param text 二维码内容
	 * @param width 二维码宽度（像素）
	 * @param height 二维码高宽度（像素）
	 * @param filePath 二维码生成存储路径
	 * @throws WriterException
	 * @throws IOException
	 */
    public static byte[] generate(String text, int width, int height) throws WriterException, IOException {
    	QRCodeWriter qrCodeWriter = new QRCodeWriter();
    	
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
		
		MatrixToImageWriter.writeToStream(bitMatrix, "PNG", ous);
        
		return ous.toByteArray();
    }

	
	public static void main(String[] args) {
        try {
            //generateQRCodeImage("This is my first QR Code", 350, 350, QR_CODE_IMAGE_PATH);
            File file = new File(QR_CODE_IMAGE_PATH);
            OutputStream ops = new FileOutputStream(file);
            generateQRCodeStream("This is my first QR Code", 350, 350, ops);
            ops.close();
        } catch (WriterException e) {
            System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
        }
		
	}
	
 
}